package com.nintendo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nintendo.base.BaseInfoProperties;
import com.nintendo.mapper.ChatMessageMapper;
import com.nintendo.pojo.ChatMessage;
import com.nintendo.pojo.netty.ChatMsg;
import com.nintendo.service.ChatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class ChatMessageServiceImpl extends BaseInfoProperties implements ChatMessageService {
    @Resource
    private ChatMessageMapper chatMessageMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void saveMsg(ChatMsg chatMsg) {
        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(chatMsg,chatMessage);
        chatMessage.setId(chatMsg.getMsgId());
        log.info( "保存消息：" + chatMessage);
        chatMessageMapper.insert(chatMessage);
        String receiverId = chatMsg.getReceiverId();
        String senderId = chatMsg.getSenderId();
        // 通过redis累加信息接受者的对应记录
//        redis.incrementHash(CHAT_MSG_LIST + ":" + receiverId, senderId, 1);
    }

    @Override
    public List<ChatMessage> findChatMessageListByPage(Integer pageNum, Integer pageSize, String myId, String friendId) {
        PageHelper.startPage(pageNum,pageSize);
        List<ChatMessage> chatMessageListByPage = chatMessageMapper.findChatMessageListByPage(myId, friendId);
        PageInfo<ChatMessage> pageInfo = new PageInfo<>(chatMessageListByPage);
        return pageInfo.getList();
    }

    @Override
    public List<ChatMessage> findChatMessageListAll(String myId, String friendId) {
        List<ChatMessage> chatMessageListAll = chatMessageMapper.findChatMessageListAll(myId,friendId);
        return chatMessageListAll;
    }

    @Override
    public Integer incrUserMessage(String myId, String friendId) {
        Object unReadMessageCount = redisTemplate.opsForValue().get(USER_MESSAGE + myId + ":" + friendId);
        if(unReadMessageCount==null){
            redisTemplate.opsForValue().set(USER_MESSAGE + myId + ":" + friendId,1);
        }else{
            redisTemplate.opsForValue().increment(USER_MESSAGE + myId + ":" + friendId);
        }
        Object unReadMessageCount1 = redisTemplate.opsForValue().get(USER_MESSAGE + myId + ":" + friendId);
        return Integer.parseInt(unReadMessageCount1.toString());
    }

    @Override
    public void clearMyUnReadCounts(String myId, String friendId) {
        redisTemplate.opsForValue().set(USER_MESSAGE + myId + ":" + friendId,0);
        log.info("清空未读消息：" + USER_MESSAGE + myId + ":" + friendId);
    }
}
